<?php

namespace app\index;

use PHPMailer\PHPMailer\PHPMailer;
use think\Controller;

class Common extends Controller {
    protected function initialize(){
        //后台——系统设置——系统设置开启限制访问站点时，跳转到指定链接
        if (get_system_val('forbidden') == 1 && $this->binarySearch()){
//            $this->redirect("https://www.youtube.com/");# 重定向到指定地址
            abort(404, '');# 抛出404异常
        }

        $this->pvInc();

        $this->assign('site_info',$this->getSiteInfo());

        $companyInfo = $this->getCompanyInfo();
        $this->assign('company_info',$companyInfo);


        $product_category = $this->getProductsCategory();
        $this->assign('category_product',list_to_tree($product_category['list']));
        $this->assign('recommend_products',$product_category['recommended']);

        $section = $this->getSection();
        $this->assign('top',$section['list']);
        $this->assign('recommend_section',$section['recommend']);
    }

    /**
     * 获取内容栏目
     * @return array
     */
    private function getSection(){
        $recommend = [];
        $list = db('section')
            ->where('status',1)
            ->field('status,sort,create_time,update_time',true)
            ->order('sort','asc')
            ->cache(60)
            ->select();
        if (!empty($list)){
            foreach ($list as $k => $v){
                $list[$k]['url'] = url($v['url']);

                if ($v['is_recommended'] == 1 && $v['pid'] == 0){
                    array_push($recommend,$list[$k]);
                }
            }
        }

        $list = list_to_tree($list);

        return ['list' => $list, 'recommend' => $recommend];
    }

    /**
     * 获取公司信息
     * @return array|null|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getCompanyInfo(){
        $info = db('company')
            ->where('id',1)
            ->cache(60)
            ->find();

        $info['contact'] = array_filter(explode(',',$info['contact']));

        $info['phone'] = explode(',', $info['phone']);

        if (!empty($info['email'])) {
            $info['email'] = explode(',', $info['email']);
        }


        return $info;
    }

    /**
     * 获取站点信息
     * @return mixed
     */
    public function getSiteInfo(){
        $site_info = db('site')
            ->where('id',1)
            ->field('id',true)
            ->cache(60)
            ->find();
        return $site_info;
    }

    /**
     * 获取产品分类
     * @return array
     */
    public function getProductsCategory(){

        $where[] = ['is_del','=',0];
        $where[] = ['status','=',1];

        $list = db('category_product')
            ->where($where)
            ->field('id,pid,level,intro,cover,name,seo_link,is_recommended')
            ->order('sort','asc')
            ->cache(60)
            ->select();

        $recommended = [];

        if (!empty($list)){
            foreach ($list as $k => $v){
                if ($v['level'] == 1) {
                    $v['link'] = url('index/product/category');
                } else {
                    $v['link'] = !empty($v['seo_link']) ? url('index/product/index',['category' => $v['seo_link']]) : url('index/product/index',['category' => $v['id']]);
                }
                $list[$k]['link'] = $v['link'];
                if ($v['is_recommended'] == 1 && $v['level'] == 1){
                    array_push($recommended,$v);
                }
            }
        }
        return ['list' => $list, 'recommended' => $recommended];
    }

    /**
     * 获取政策文章
     * @param $id 文章ID。 1：隐私政策；2：物流政策
     * @return mixed
     */
    public function getPolicy($id){
        $policy = db('policy')
            ->where('id',$id)
            ->where('is_del',0)
            ->where('status',1)
            ->field('id,title')
            ->order('sort','asc')
            ->find();
        return $policy;
    }

    /**
     * 获取栏目seo信息
     * @param int/string $section_id 栏目id
     */
    protected function seoContent($section_id){
        $section = db('section')
            ->where('id',$section_id)
            ->find();
        $this->assign('seo_keywords',$section['seo_keywords']);
        $this->assign('seo_describe',$section['seo_describe']);
        $this->assign('section_banner',$section['banner']);
        $this->assign('section_info',$section);
    }

    protected function binarySearch(){
        $arr = db('forbidden')
            ->field('start,end')
            ->select();
        $arr = tree_array_sort($arr,'start',SORT_ASC);

        foreach ($arr as $k => $v){
            $arr[$k]['start'] = long2ip($v['start']);
            $arr[$k]['end'] = long2ip($v['end']);
        }

        $target = real_ip();
        $low = 0;
        $high = count($arr) - 1;
        while ($low <= $high){
            $mid = floor(($low + $high) / 2);
            #找到元素
            if ($target >= $arr[$mid]['start'] && $target <= $arr[$mid]['end']) {
                return true;
            }
            #中元素比目标大，查找start
            if ($target < $arr[$mid]['start']) {
                $high = $mid - 1;
            }
            #中元素比目标小，查找end
            if ($target > $arr[$mid]['start']) {
                $low = $mid + 1;
            }
        }
        #查找失败
        return false;
    }

    /**
     * 站点访问量
     */
    protected function pvInc(){
        //如果cookie为空，则视为新的用户访问，访问量 + 1
        if (empty(cookie('pv'))){
            //写入访问记录
            db('pv')->insert(['ip' => ip2long(real_ip()), 'create_time' => time()]);
            //设置cookie，过期时间30分钟
            cookie('pv',qa_encrtyp(ip2long(real_ip())),1800);
        }
    }

    function sendEmail(){
        $mail = new PHPMailer();
        $mail->isSMTP();
        $mail->CharSet = 'UTF-8';
        $mail->Host = get_system_val('smtp_host');
        //开启auth验证，这个需要填写true
        $mail->SMTPAuth = true;
        //你的网易邮箱账号
        $mail->Username = get_system_val('email_username');
        //授权密码，你在网易设置取到的授权密码，不是你的邮箱登录密码
        $mail->Password = get_system_val('email_pwd');;
        //当我们设置的端口是465的时候，需要进行SSL验证，如果设置的端口是25的时候此项需要留空
        $mail->SMTPSecure = 'ssl';
        $mail->Port = get_system_val('smtp_port');
        //发件人的信息
        $mail->setFrom(get_system_val('email_username'), 'Sender');
        //收件人的信息
        $mail->addAddress(get_system_val('email_username'));
        //内容设置
        $mail->isHTML(true);
        $mail->Subject = '有新的询盘消息';
        $mail->Body = '有新的询盘消息，请登录网站后台查看';
        $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
        //发送邮箱
        $res = $mail->send();
        if(!$res){
            echo $mail->ErrorInfo;
        }
    }
}